//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
// 引入SDK核心类,实例化API核心类
var QQMapWX = require('../../common/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWX({
  key: 'b6af1635786ff310b0f07cba63460532' // 必填
});
var Type = [];
var TypeAll = [];
var businessPhotoString = '';
var address = '';
var BaiduX = '';
var BaiduY = '';
var setBaiduX = '';
var setBaiduY = '';
var idcardpositivePic = '';
var idcardbackPic = '';
var BaiduX5 = '';
var BaiduY5 = '';
Page({
  data: {
    color0: "#999",
    color1: "#999",
    storeType: "请选择",
    index: 0,
    businessType: ['医药保健', '数码电子', '美妆护肤', '珠宝首饰', '餐饮美食', '休闲旅游', '母婴用品', '服装/内衣', '买房租房', '农副产品', '鞋帽箱包', '酒店连锁', '卫浴厨具', '图书教材', '家居装修', '家装家居', '护理美容', '烟酒/超市', '汽车用品', '其他'],
    // 
    region: ['请选择', '', ''],
    businessData: {},
    // 红包预存
    hongBaoFlag: true,
    hongBao: "",
    // 商家数据
    uid: "",
    userType: "",
    businessId: 0,
    // 店铺头像
    imgUrl: baseJs.imgUrl,
    businessPhoto: "",
    businessAllName: "",
    detailAddress: "",
    url: "",
    // businessPhotoString:'',
    // 是否设置红包
    isSetHongBao: "",
    isSetHongBaoArr: ['暂不设置易易红包', '设置易易红包'],
    // 红包额度
    hongBaoEDu: "",
    //购买易易红包
    payFlag: true,
    // 输入支付密码
    //是否展示密码输入层
    showPayPwdInput: false,
    //输入的密码
    payPasswords: "",
    //文本框焦点
    Focus: false,
    // 是否已经设置支付密码
    isAlreadyPayPassword: "",
    // 订单号
    orderNumber: "",
    disabled: {
      type: "",
      value: "",
    },
    storeDetail: "",
    map: "",
    X: "",
    Y: "",
    // 获取当前位置
    location: '我的位置',
    province: '',  //省
    city: '',      //市
    district: '',   //区
    street: '',     //路  
    street_number: '', //号
    latitude: '',
    longitude: '',
    address: '',
    hidden: true,
    // 上传营业资质图片
    imgUrl: baseJs.imgUrl,
    imgStr: "",
    imgList: [],
    imgStrB: "",
    imgListB: [],
    imgStrC: "",
    imgListC: [],
    opacity: "0.5",
    agreeAndReceipt: "0",
    diliweizhi:"请选择"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var region = this.data.region;
    this.setData({
      uid: wx.getStorageSync('uid'),
      userType: wx.getStorageSync('userType'),
    })
    this.GetBusinessDataSet();
    // this.formSubmit();
    this.GetBusinessType();
    this.getLocation();
  },
  // 接受协议
  agreeAndReceipt: function (e) {
    if (e.detail.value.length == 0) {
      this.setData({
        agreeAndReceipt: "0",
        opacity: 0.5
      })
    } else {
      this.setData({
        agreeAndReceipt: "1",
        opacity: 1
      })
    }
  },
  // 跳转 易易部落用户服务协议
  navigate: function () {
    wx.navigateTo({
      url: '/packageA/yonghuxieyi',
    })
  },
  navigateTo: function () {
    wx.navigateTo({
      url: '/packageA/yinsizhengce',
    })
  },
  // 获取用户地理位置
  getUserLocation: function () {
    var vm = this;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] == undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.getSetting({
                  success: function (dataAu) {
                    // console.log(dataAu.errMsg);
                    if (dataAu.errMsg == 'getSetting:ok') {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      console.log(vm);
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] != undefined) {
          //调用wx.getLocation的API
          // console.log(res.authSetting['scope.userLocation']);
          this.getLocation();
        }
        else {
          //调用wx.getLocation的API
          this.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    var vm = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res);
        BaiduX5 = res.latitude;
        BaiduY5 = res.longitude;
        qqmapsdk = new QQMapWX({
          key: 'b6af1635786ff310b0f07cba63460532'
        });
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          // coord_type: 3,//baidu经纬度
          success: function (res) {
            let province = res.result.address_component.province
            let city = res.result.address_component.city
            let district = res.result.address_component.district
            let street = res.result.address_component.street
            let street_number = res.result.address_component.street_number
            vm.setData({
              location: '',
              province: province,
              city: city,
              district: district,
              street: street,
              street_number: street_number,
              latitude: res.latitude,
              longitude: res.longitude
            })
          },
          fail: function (res) {
            console.log('网络错误');
          },
        })
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },

  // 得到商家类型   
  GetBusinessType: function () {
    var that = this;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetBusinessType"),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        TypeAll = json;
        // console.log(TypeAll);
        for (var i = 0; i < TypeAll.length; i++) {
          Type.push(TypeAll[i].TypeName);
        }
        // console.log(Type);
        that.setData({
          Type: Type,
        })
      }
    })
  },

  //更改地理位置
  getmap(e) {
    // wx.getSetting({
    //   success: function (res) {
    //     var statu = res.authSetting;
    //     if (!statu['scope.userLocation']) {
    //       wx.showModal({
    //         title: '发布需要授权定位功能',
    //         content: '请确认授权，否则地图功能将无法使用',
    //         success: function (tip) {
    //           if (tip.confirm) {
    //             console.log(tip.confirm)
    //             wx.openSetting({
    //               success: function (data) {
    //                 if (data.authSetting["scope.userLocation"] === true) {
    //                   app.ShowToast("授权成功")
    //                 } else {
    //                   app.ShowToast("授权失败，请重新点击")
    //                 }
    //               },
    //               fail: function (data) {
    //                 console.log(data)
    //               }
    //             })
    //           } else {
    //             app.ShowToast("授权失败，请重新点击")
    //           }
    //         },
    //       })
    //     }
    //   }
    // });
    var that = this;
    var BaiduX4 = '';
    var BaiduY4 = '';

    if (parseFloat(BaiduY) < 1 || parseFloat(BaiduX) < 1 || isNaN(parseFloat(BaiduY)) || isNaN(parseFloat(BaiduX))) {
      // BaiduX4 = parseFloat(baseJs.convertBD09ToGCJ02(parseFloat(BaiduY), parseFloat(BaiduX))[0]);
      // BaiduY4 = parseFloat(baseJs.convertBD09ToGCJ02(parseFloat(BaiduY), parseFloat(BaiduX))[1]);
      BaiduX4 = BaiduY5
      BaiduY4 = BaiduX5
    } else {
      BaiduX4 = parseFloat(baseJs.convertBD09ToGCJ02(parseFloat(BaiduY), parseFloat(BaiduX))[0]);
      BaiduY4 = parseFloat(baseJs.convertBD09ToGCJ02(parseFloat(BaiduY), parseFloat(BaiduX))[1]);
    }
    console.log(BaiduX)
    console.log(BaiduY)
    console.log(BaiduX4)
    console.log(BaiduY4)
    console.log(BaiduX5)
    wx.chooseLocation({
      longitude: BaiduX4,
      latitude: BaiduY4,
      success: function (res) {
        console.log(res);
        var reg = /.+?(省|市|自治区|自治州|县|区)/g;
        var addr = res.address.match(reg);
        that.setData({
          address: res.name, //调用成功直接设置地址
          'region[0]': addr[0],
          'region[1]': addr[1],
          'region[2]': addr[2],
          resident: res.name,
          longitude: res.longitude,
          latitude: res.latitude,
          diliweizhi:"已经选择，点击查看"
        })
        setBaiduX = res.longitude;
        setBaiduY = res.latitude;
      }
    })
  },
  
  // 查看地理位置
  AddressInput: function () {
    var that = this;
    var BaiduX1 = parseFloat(BaiduX);
    var BaiduY1 = parseFloat(BaiduY);
    var region = this.data.region;
    var BaiduX2 = parseFloat(baseJs.convertBD09ToGCJ02(BaiduY1, BaiduX1)[0]);
    var BaiduY2 = parseFloat(baseJs.convertBD09ToGCJ02(BaiduY1, BaiduX1)[1]);
    console.log(BaiduX2);
    console.log(BaiduY2);
    // 调用接口
    qqmapsdk.geocoder({
      address: region,
      success: function (res) {
        console.log(res);
        wx.openLocation({
          latitude: BaiduY2,
          longitude: BaiduX2,
          scale: 28,
        })
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  // 获取商家数据
  GetBusinessDataSet: function () {
    var that = this;
    var uid = this.data.uid;
    var isSetHongBao = this.data.isSetHongBao;
    var businessData = this.data.businessData;
    var hongBao = this.data.hongBao;
    var region = this.data.region;
    var index = this.data.index;
    // var businessPhoto = this.data.businessPhoto;
    var CompanyName = '';
    var BusinessDescribe = '';
    var address = '';
    var imgList = this.data.imgList;
    var imgListB = this.data.imgListB;
    var imgListC = this.data.imgListC;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetBusinessDataSet&SJID=" + uid),
      success: function (res) {
        console.log(JSON.parse(baseJs.decryUrl(res.data)));
        businessData = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        region[0] = businessData.ProvinceName;
        region[1] = businessData.CityName;
        region[2] = businessData.AreaName;
        CompanyName = businessData.businessAllName;
        address = businessData.SuppleAddress
        // address = businessData.SuppleAddress.replace(/省|市|自治区|特别行政区|壮族|回族|维吾尔/g,"");
        // console.log(address);
        hongBao = businessData.GiftTotle;
        businessPhotoString = businessData.BusinessShopImg;
        isSetHongBao = businessData.IsOpenCoupon;
        BaiduY = businessData.BaiduY;
        BaiduX = businessData.BaiduX;
        idcardpositivePic = businessData.IdCardpositivePic;
        idcardbackPic = businessData.IdCardbackPic;
        var json = JSON.parse(baseJs.decryUrl(res.data)).ResultData.BusinesslicensePic.split(';');
        for (var i = 0; i < json.length; i++) {
          if (json[i].length > 0) {
            imgList.push(json[i]);
          }
        }
        var jsonB = JSON.parse(baseJs.decryUrl(res.data)).ResultData.ShopStorePic.split(';');
        for (var i = 0; i < jsonB.length; i++) {
          if (jsonB[i].length > 0) {
            imgListB.push(jsonB[i]);
          }
        }
        var jsonC = JSON.parse(baseJs.decryUrl(res.data)).ResultData.BusinessDevelopersWitnessImg.split(';');
        for (var i = 0; i < jsonC.length; i++) {
          if (jsonC[i].length > 0) {
            imgListC.push(jsonC[i]);
          }
        }
        if (businessData.businessType == 0) {
          index = 0;
        } else {
          index = businessData.businessType - 1;
        }
        that.setData({
          businessData: businessData,
          region: region,
          index: index,
          CompanyName: CompanyName,
          BusinessDescribe: businessData.BusinessDescribe,
          businessPhotoString: businessPhotoString,
          address: address,
          imgList: imgList,
          imgListB: imgListB,
          imgListC: imgListC,
          idcardpositivePic: idcardpositivePic,
          idcardbackPic: idcardbackPic,
        })
        if (region[0] == "请选择") {
          that.setData({
            color0: "#999",
            hidden: false
          })
        } else {
          that.setData({
            color0: "#333"
          })
        }
        // console.log(businessData);
      }
    })
  },
  // 店铺类型
  bindPickerChange: function (e) {
    console.log(e)
    this.setData({
      index: e.detail.value,
      Focus: false,
    })
    wx.hideKeyboard()//收起键盘
  },
  // 省市区 店铺地址
  bindRegionChange: function (e) {
    console.log(e.detail.value)
    this.setData({
      region: e.detail.value,
      Focus: false,
    })
    wx.hideKeyboard()//收起键盘
  },

  // 保存设置
  formSubmit: function (e) {
    var that = this;
    var region = this.data.region;
    var index = (this.data.index - 0) + 1;
    var uid = this.data.uid;
    var typeid = TypeAll[index].Id;
    var BaiduX3 = baseJs.gtb(setBaiduX, setBaiduY)[0];
    var BaiduY3 = baseJs.gtb(setBaiduX, setBaiduY)[1];
    var imgList = this.data.imgList;
    var imgStr = this.data.imgStr;
    var imgListB = this.data.imgListB;
    var imgStrB = this.data.imgStrB;
    var imgListC = this.data.imgListC;
    var imgStrC = this.data.imgStrC;
    imgStr = '';
    imgStrB = '';
    imgStrC = '';
    var agreeAndReceipt = this.data.agreeAndReceipt;
    var businessPhotoString = this.data.businessPhotoString;
    if (agreeAndReceipt == "0") {
      wx.showToast({
        title: "请同意并接受以上协议！",
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    for (var i = 0; i < imgList.length; i++) {
      imgStr = imgStr + imgList[i] + ';';
    }
    for (var i = 0; i < imgListB.length; i++) {
      imgStrB = imgStrB + imgListB[i] + ';';
    }
    for (var i = 0; i < imgListC.length; i++) {
      imgStrC = imgStrC + imgListC[i] + ';';
    }
    console.log(businessPhotoString)
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=BusinessDataSet"),
      method: 'post',
      data: baseJs.json2Form({
        SJID: uid,
        CompanyName: e.detail.value.name,
        BusinessType: typeid,
        ProvinceName: region[0],
        CityName: region[1],
        AreaName: region[2],
        SuppleAddress: e.detail.value.detailAddress,
        BusinessDescribe: e.detail.value.storeDetail,
        address: e.detail.value.detailAddress,
        RelatedLinks: e.detail.value.url,
        BusinessShopImg: businessPhotoString,
        BaiduX: BaiduX3,
        BaiduY: BaiduY3,
        BusinesslicensePic: imgStr,
        ShopStorePic: imgStrB,
        BusinessDevelopersWitnessImg: imgStrC,
        IdCardbackPic: idcardbackPic,
        IdCardpositivePic: idcardpositivePic,

      }),

      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        // console.log(BaiduX);
        // console.log(BaiduY);
        // console.log(res);
        if (res.data.ResultFlag == 1) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 1000)
        } else {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }

      }

    })
  },
  // 店铺头像
  chooseImg: function (e) {
    var that = this;
    var base64 = this.data.base64;
    var imgSrc = this.data.imgSrc;
    var imgUrl = this.data.imgUrl;
    var businessPhotoString = this.data.businessPhotoString;
    wx.chooseImage({
      // 最多可以选择的图片张数，默认9
      count: 1,
      // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ['original', 'compressed'],
      // 可以指定来源是相册还是相机，默认二者都有
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        console.log(businessPhotoString);
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths[0];
        // base64 = wx.arrayBufferToBase64(res.data);
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0], //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            // console.log('data:image/png;base64,' + res.data)
            wx.request({
              url: baseJs.api + baseJs.encryUrl("method=LoadPic"),
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              method: 'post',
              data: baseJs.json2Form({
                HeadImage: res.data,
                type: 11,
              }),
              success: function (res) {
                console.log(res);
                // businessPhoto.push(imgUrl + res.data.ResultData);
                businessPhotoString = imgUrl + res.data.ResultData;
                that.setData({
                  // businessPhoto: businessPhoto,
                  businessPhotoString: businessPhotoString,
                })
                console.log(businessPhotoString)
              }
            })
          }
        })

      }
    })
  },

  // x删除图片
  delTap: function (e) {
    var imgList = this.data.imgList;
    imgList.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      imgList: imgList,
    })
  },
  // 营业执照
  chooseImgA: function (e) {
    var that = this;
    var base64 = this.data.base64;
    var imgSrc = this.data.imgSrc;
    var imgUrl = this.data.imgUrl;
    var imgList = this.data.imgList;
    wx.chooseImage({
      // 最多可以选择的图片张数，默认9
      count: 9,
      // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ['original', 'compressed'],
      // 可以指定来源是相册还是相机，默认二者都有
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        that.upLoadpic(tempFilePaths, imgList, 5);

      }
    })
  },
  // x删除图片
  delTapB: function (e) {
    var imgListB = this.data.imgListB;
    imgListB.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      imgListB: imgListB,
    })
  },
  // 店铺实景图
  chooseImgB: function (e) {
    var that = this;
    var base64 = this.data.base64;
    var imgSrc = this.data.imgSrc;
    var imgUrl = this.data.imgUrl;
    var imgListB = this.data.imgListB;
    wx.chooseImage({
      // 最多可以选择的图片张数，默认9
      count: 9,
      // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ['original', 'compressed'],
      // 可以指定来源是相册还是相机，默认二者都有
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        that.upLoadpic(tempFilePaths, imgListB, 2);
      }
    })
  },
  upLoadpic: function (a, b, type) {
    console.log(a);
    console.log(b);

    var that = this;
    var base64 = this.data.base64;
    var imgSrc = this.data.imgSrc;
    var imgUrl = this.data.imgUrl;
    // var imgListB = this.data.imgListB;

    if (a.length > 0) {
      wx.getFileSystemManager().readFile({
        filePath: a[0], //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => { //成功的回调
          // console.log('data:image/png;base64,' + res.data)
          wx.request({
            url: baseJs.api + baseJs.encryUrl("method=LoadPic"),
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            method: 'post',
            data: baseJs.json2Form({
              HeadImage: res.data,
              type: type,
            }),
            success: function (res) {
              console.log(res);
              b.push(imgUrl + res.data.ResultData);
              if (type == 5) {
                that.setData({
                  imgList: b,
                })
              }
              if (type == 2) {
                console.log('2')
                that.setData({
                  imgListB: b,
                })
              }
              if (type == 22) {
                console.log('22')
                that.setData({
                  imgListC: b,
                })
              }

              a.shift()
              // 检测是否需要递归
              if (a.length > 0) {
                that.upLoadpic(a, b, type)
              }
              console.log(res.data.ResultData)
            }
          })
        }
      })
    } else {

    }



  },

  // x删除图片
  delTapC: function (e) {
    var imgListC = this.data.imgListC;
    imgListC.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      imgListC: imgListC,
    })
  },
  // 合照
  chooseImgC: function (e) {
    var that = this;
    var base64 = this.data.base64;
    var imgSrc = this.data.imgSrc;
    var imgUrl = this.data.imgUrl;
    var imgListC = this.data.imgListC;
    wx.chooseImage({
      // 最多可以选择的图片张数，默认9
      count: 9,
      // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ['original', 'compressed'],
      // 可以指定来源是相册还是相机，默认二者都有
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        that.upLoadpic(tempFilePaths, imgListC, 22);

      }
    })
  },
  // 身份证反面
  chooseImgD: function (e) {
    var that = this;
    var base64 = this.data.base64;
    var imgSrc = this.data.imgSrc;
    var imgUrl = this.data.imgUrl;
    // var idcardpositivePic = this.data.idcardpositivePic;
    wx.chooseImage({
      // 最多可以选择的图片张数，默认9
      count: 1,
      // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ['original', 'compressed'],
      // 可以指定来源是相册还是相机，默认二者都有
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        console.log(idcardpositivePic);
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths[0];
        // base64 = wx.arrayBufferToBase64(res.data);
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0], //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            // console.log('data:image/png;base64,' + res.data)
            wx.request({
              url: baseJs.api + baseJs.encryUrl("method=LoadPic"),
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              method: 'post',
              data: baseJs.json2Form({
                HeadImage: res.data,
                type: 3,
              }),
              success: function (res) {
                console.log(res);
                // businessPhoto.push(imgUrl + res.data.ResultData);
                idcardpositivePic = imgUrl + res.data.ResultData;
                that.setData({
                  // businessPhoto: businessPhoto,
                  idcardpositivePic: idcardpositivePic,
                })


              }
            })
          }
        })

      }
    })
  },
  // 身份证正面
  chooseImgE: function (e) {
    var that = this;
    var base64 = this.data.base64;
    var imgSrc = this.data.imgSrc;
    var imgUrl = this.data.imgUrl;
    // var idcardbackPic = this.data.idcardbackPic;
    wx.chooseImage({
      // 最多可以选择的图片张数，默认9
      count: 1,
      // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ['original', 'compressed'],
      // 可以指定来源是相册还是相机，默认二者都有
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        console.log(idcardbackPic);
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths[0];
        // base64 = wx.arrayBufferToBase64(res.data);
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0], //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            // console.log('data:image/png;base64,' + res.data)
            wx.request({
              url: baseJs.api + baseJs.encryUrl("method=LoadPic"),
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              method: 'post',
              data: baseJs.json2Form({
                HeadImage: res.data,
                type: 3,
              }),
              success: function (res) {
                console.log(res);
                // businessPhoto.push(imgUrl + res.data.ResultData);
                idcardbackPic = imgUrl + res.data.ResultData;
                that.setData({
                  idcardbackPic: idcardbackPic,
                })
              }
            })
          }
        })

      }
    })
  },

  // 是否设置易易红包
  pickerSetHongBao: function (e) {
    console.log(e)
    this.setData({
      isSetHongBao: e.detail.value,
    })
  },
  // 点击购买易易红包
  buyHongBao: function () {
    var that = this;
    var uid = this.data.uid;
    var payFlag = this.data.payFlag;
    var orderNumber = this.data.orderNumber;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=BuyEnoupCreateOrder&BuyNum=100&SJID=" + uid),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data))
        console.log(json);
        if (json.ResultFlag == 1) {
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 2000
          });
          orderNumber = json.ResultData.OrderNumber;
          that.setData({
            payFlag: false,
            orderNumber: orderNumber,
          })
        } else {
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
  },
  // 支付显示
  cancelPay: function () {
    this.setData({
      payFlag: true
    })
  },
  //余额或微信 
  radioChange: function (e) {
    var payType = this.data.payType;
    payType = e.detail.value
    this.setData({
      payType: payType,
    });
  },
  // goPay
  goPay: function () {
    var that = this;
    var uid = this.data.uid;
    var orderNumber = this.data.orderNumber;
    var payType = this.data.payType;
    var isAlreadyPayPassword = this.data.isAlreadyPayPassword;
    if (payType == '') {
      wx.showToast({
        title: "请选择支付方式！",
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (payType == "0") {
      if (isAlreadyPayPassword == '1') {
        that.setData({
          showPayPwdInput: true,
          payFocus: true,
          payFlag: true,
        })
      } else {
        wx.showToast({
          title: "请先去设置支付密码！",
          icon: 'none',
          duration: 2000
        });
      }

    } else {
      console.log("method=BuyEnoupOrderPay&OrderNumber=" + orderNumber + "&PayType=2" + "&UID=" + uid);
      wx.request({
        url: baseJs.api + baseJs.encryUrl("method=BuyEnoupOrderPay&OrderNumber=" + orderNumber + "&PayType=2" + "&UID=" + uid),
        success: function (res) {
          var json = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
          console.log(json);
          // wx.requestPayment({
          //   timeStamp: json.ResultData.timestamp,
          //   nonceStr: json.ResultData.nonce_str,
          //   package: 'prepay_id=' + json.ResultData.prepay_id,
          //   signType: 'MD5',
          //   paySign: json.ResultData.sign,
          //   success(res) {
          //     console.log(res);
          //     wx.navigateBack({
          //       delta: 1
          //     })
          //   },
          //   fail(res) {
          //     console.log(res);
          //     wx.showToast({
          //       title: res.err_desc,
          //       icon: 'none',
          //       duration: 2000
          //     });
          //   }
          // })

        }
      })
    }

  },

  //显示支付密码输入层
  showInputLayer: function () {
    this.setData({
      showPayPwdInput: true,
      payFocus: true
    });
  },

  //隐藏支付密码输入层
  cancelInputPasswords: function () {
    var val = this.data.payPasswords;
    this.setData({
      showPayPwdInput: false,
      payFocus: false,
      payPasswords: ''
    });
  },
  // 获取焦点
  getFocus: function () {
    this.setData({
      payFocus: true
    });
  },
  //输入密码,监听
  inputPwd: function (e) {
    this.setData({
      payPasswords: e.detail.value
    });
  },
  //输入密码 确定 
  surePasswords: function () {
    var that = this;
    var uid = this.data.uid;
    var payPasswords = this.data.payPasswords;
    var orderNumber = this.data.orderNumber;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=CheckMyTradePassword&UID=" + uid + "&TradePassword=" + payPasswords),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data));
        console.log(json);
        if (json.ResultFlag == 1) {
          console.log("method=BuyEnoupOrderPay&OrderNumber=" + orderNumber + "&PayType=0" + "&UID=" + uid);
          // wx.request({
          //   url: baseJs.api + baseJs.encryUrl("method=BuyEnoupOrderPay&OrderNumber=" + orderNumber + "&PayType=0" + "&UID=" + uid),
          //   success: function (res) {
          //     var json = JSON.parse(baseJs.decryUrl(res.data))
          //     console.log(json);
          //     if (json.ResultData == "success") {
          //       wx.showToast({
          //         title: json.ResultMsg,
          //         icon: 'none',
          //         duration: 2000
          //       });
          //       that.GetBusinessDataSet();
          //     } else {
          //       wx.showToast({
          //         title: json.ResultMsg,
          //         icon: 'none',
          //         duration: 2000
          //       });
          //     }
          //   }
          // })
        } else {
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
  },
  // 
})